import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:openchina/constants/constants.dart'
    show AppInfo, AppUrls, AppColors;
import 'package:flutter/cupertino.dart';
import 'package:openchina/utils/data_util.dart';
import 'package:openchina/utils/net_util.dart';

class LoginWebPage extends StatefulWidget {
  @override
  _LoginWebPageState createState() => _LoginWebPageState();
}

class _LoginWebPageState extends State<LoginWebPage> {
  FlutterWebviewPlugin _flutterWebviewPlugin = FlutterWebviewPlugin();
  bool _isLoading = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //监听url变化
    _flutterWebviewPlugin.onUrlChanged.listen((url) {
//      https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=K1TI5ZxqRUgx50vlAHR7&redirect_uri=https://www.baidu.com/

      print('LoginWebPage onUrlChanged: $url');
      if(mounted){//转菊花消失  mounted 确保当前weiget 在当前渲染树上
        setState(() {
          _isLoading = false;
        });
      }
//      https://www.baidu.com/?code=Yq4PTm&state=
      if(url!=null&&url.length>0&&url.contains('?code=')){
        //登录成功状态
        //提取code授权码
        String code = url.split('?')[1].split('&')[0].split('=')[1];
        print('授权code: $code');
        Map<String,dynamic> params = Map<String,dynamic>();
        params['client_id']=AppInfo.CLIENT_ID;
        params['client_secret']=AppInfo.CLIENT_SECRET;
        params['grant_type']=AppInfo.AUTHORIZATION_CODE;
        params['redirect_uri']=AppInfo.REDIRECT_URI;
        params['code']='$code';
        params['dataType']=AppInfo.JSON;
        NetUtil.get(AppUrls.OAUTH2_TOKEN,params).then((data){
//          {"access_token":"8644a7e1-a097-496d-9891-e29a9419c983","refresh_token":"0ffc807d-ffc8-4345-90f0-1156726575b4","uid":1991319,"token_type":"bearer","expires_in":604799}
          print('获取token：$data');
          if(data!=null){
            Map<String,dynamic> map = json.decode(data);
            if(map!=null&&map.isNotEmpty){
              //保存token 等 直接保存map
              DataUtil.saveLoginInfo(map);
              //弹出当前路由并且返回双方约定字段通知我的界面进行刷新
              Navigator.pop(context,'refresh');
            }
          }
        });
      }
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _flutterWebviewPlugin.close();
  }
  @override
  Widget build(BuildContext context) {
//    /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
    List<Widget> _appBarTitle = [
      Text(
        '登录开源中国',
        style: TextStyle(
          color: Color(AppColors.APPBAR),
        ),
      ),
    ];
    if (_isLoading) {
      _appBarTitle.add(
        SizedBox(
          width: 10.0,
        ),
      );
      _appBarTitle.add(CupertinoActivityIndicator());
    }
    return WebviewScaffold(
      url: AppUrls.OAUTH2_AUTHORIZE +
          '?response_type=code&client_id=' +
          AppInfo.CLIENT_ID +
          '&redirect_uri=' +
          AppInfo.REDIRECT_URI,
      appBar: AppBar(
        title: Row(
          children: _appBarTitle,
        ),
      ),
      withJavascript: true,//允许执行js
      withLocalStorage: true,//允许本地存储
      withZoom: true,//允许网页放大缩小
    );
  }
}
